<template>
  <scroll-view class="message-list-container" scroll-y="true" :scroll-into-view="scrollView"
               :refresher-enabled="!isServerCompleted" @refresherrefresh="refresh" :scroll-top="scrollTop"
               :refresher-triggered="triggered" @scroll="scroll">
    <view id="message-scroll" style="width:100%">
      <view class="no-message" v-if="isCompleted">没有更多啦</view>
      <view v-for="(item, index) in messageList" :key="item.ID" class="t-message">
        <view v-if="conversation.type !== '@TIM#SYSTEM'" :id="item.ID">
          <view class="t-message-item">
            <view v-if="tooltipShow" @click="handleEditToggleAvatar">
              <view class="label-pop " v-if="tooltipMsgId === item.ID"
                    :class="{
									'label-self-body': item.flow == 'out',
									'label-recieve-body': item.flow == 'in',
									'bottom-text': item.type == 'TIMTextElem',
									'bottom-image': item.type == 'TIMImageElem',
									'bottom-video': item.type == 'TIMVideoFileElem',
								}">
                <view class="label-pop-mask">
                  <!-- 	<view class="copymessage"
                    v-if="item.type === 'TIMTextElem'|| item.type === 'TIMFaceElem'"
                    @click="copyMessage"> <text>复制｜</text>
                  </view> -->
                  <!-- 	<view class="deletemessage" @click="deleteMessage"> <text>删除</text>
                  </view> -->
                  <!-- 	<view class="pop_top">
                    <view class="revokemessage" @click="copyMessage">
                      <text class="icon icon-fuzhi"></text>
                      <text class="text_label">{{lang.chat_copy}}</text>
                    </view>
                    <view class="revokemessage" @click="revokeMessage">
                      <text class="icon icon-zhuanfa"></text>
                      <text class="text_label">{{lang.chat_forward}}</text>
                    </view>
                    <view class="revokemessage" @click="revokeMessage">
                      <text class="icon icon-shanchutianchong"></text>
                      <text class="text_label">{{lang.chat_delete}}</text>
                    </view>
                  </view> -->
                  <view class="pop_bottom">
                    <!-- 	<view class="revokemessage" @click="revokeMessage">
                      <text class="icon icon-duoxuan-04"></text>
                      <text class="text_label">{{lang.chat_mul_choose}}</text>
                    </view> -->
                    <view class="revokemessage" v-if="item.type == 'TIMTextElem'" @click="copyMessage">
                      <text class="icon icon-fuzhi"></text>
                      <text class="text_label">{{lang.chat_copy}}</text>
                    </view>
                    <view class="revokemessage" v-if="item.flow == 'out' && isShowRevoke" @click="revokeMessage">
                      <text class="icon icon-chehuisekuai"></text>
                      <text class="text_label">{{lang.chat_recall}}</text>
                    </view>
                    <view class="revokemessage" @click="handleEditToggleAvatar">
                      <text class='icon icon-shousuoshangjiantou'></text>
                      <text class="text_label">{{lang.chat_back}}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>

            <TUI-TipMessage v-if="item.type === 'TIMGroupTipElem' && !item.isRevoked && !item.isDeleted"
                            :message="item" :lang="lang" :groupUser="groupUserDict">
            </TUI-TipMessage>
            <view class="chatTime">
              <text class="chatTime-text">{{getHistoryChatTime(item.time *1000,i18n,lang)}}</text>
            </view>
            <view v-if="item.isRevoked" class="chatTime">
              <text v-if="item.flow == 'out'"
                    class="chatTime-text">{{lang.chat_recall_message_self}}</text>
              <text v-if="item.flow == 'in' && item.conversationType == 'GROUP'"
                    class="chatTime-text">{{item.nick}}{{lang.chat_recall_message}}</text>
              <text v-else-if="item.flow == 'in'"
                    class="chatTime-text">{{item.nick}}{{lang.chat_recall_message}}</text>
            </view>
            <view v-if="item.type !== 'TIMGroupTipElem' && !item.isRevoked"
                  :class="item.flow==='out'? 't-self-message':'t-recieve-message'"
                  style="display: flex;align-items:flex-start">
              <image class="t-message-avatar" v-if="item.flow==='in' && conversation.type == 'C2C'"
                     :src="item.avatar" @error="handleImageError(index)">
              </image>
              <image class="t-message-avatar"
                     v-else-if="item.flow==='in' && groupUserDict[item.from].UserAvatar != '' && conversation.type == 'GROUP'"
                     :src="groupUserDict[item.from].UserAvatar" @error="handleImageError(item.from, 'GROUP')">
              </image>
              <image class="t-message-avatar" v-else-if="item.flow==='in' && conversation.type == 'GROUP' && item.avatar == ''"
                     src='/static/images/avatar.jpg'>
              </image>
              <image class="t-message-avatar" v-else-if="item.flow==='in' && conversation.type == 'GROUP'"
                     :src="item.avatar" @error="handleImageError(index)">
              </image>
              <view>
                <view class="nick" v-if="item.flow==='out'" style="text-align:right">
                  <label v-if="item.nick != ''">{{item.nick}}</label>
                  <label v-else>{{groupUserDict[item.from].UserName}}</label>
                </view>
                <view class="nick" v-if="item.flow==='in'">
                  <label v-if="item.nick != ''">{{item.nick}}</label>
                  <label v-else>{{groupUserDict[item.from].UserName}}</label>
                </view>
                <view @longtap="handleLongPress(item)">
                  <TUI-TextMessage v-if="item.type === 'TIMTextElem'" :message="item"
                                   :isMine="item.flow==='out'" :lang="lang"></TUI-TextMessage>
                  <TUI-ImageMessage v-if="item.type === 'TIMImageElem'" :message="item"
                                    :isMine="item.flow==='out'"></TUI-ImageMessage>
                  <TUI-VideoMessage v-if="item.type === 'TIMVideoFileElem'" :message="item"
                                    :isMine="item.flow==='out'"></TUI-VideoMessage>
                  <TUI-AudioMessage v-if="item.type === 'TIMSoundElem'" :message="item"
                                    :isMine="item.flow==='out'"></TUI-AudioMessage>
                  <TUI-CustomMessage v-if="item.type === 'TIMCustomElem'" :message="item"
                                     :isMine="item.flow==='out'" :lang="lang">
                  </TUI-CustomMessage>
                  <TUI-FaceMessage v-if="item.type === 'TIMFaceElem'" :message="item"
                                   :isMine="item.flow==='out'"></TUI-FaceMessage>
                  <TUI-FileMessage v-if="item.type === 'TIMFileElem'" :message="item"
                                   :isMine="item.flow==='out'"></TUI-FileMessage>
                </view>
                <view class="read-receipts" v-if="conversation.type === 'C2C' && item.flow==='out'">
                  <view v-if="item.isPeerRead" class="read">{{lang.message_read}}</view>
                  <view v-else class="unread">{{lang.message_unread}}</view>
                </view>
              </view>
              <image class="t-message-avatar" v-if="item.flow==='out' && conversation.type == 'C2C'"
                     :src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'" @error="handleImageError(index)">
              </image>
              <image class="t-message-avatar"
                     v-else-if="item.flow==='out' && groupUserDict[item.from].UserAvatar != '' && conversation.type == 'GROUP'"
                     :src="groupUserDict[item.from].UserAvatar" @error="handleImageError(item.from, 'GROUP')">
              </image>
              <image class="t-message-avatar" v-else-if="item.flow==='out' && conversation.type == 'GROUP' && item.avatar == ''"
                     src='/static/images/avatar.jpg'>
              </image>
              <image class="t-message-avatar"
                     v-else-if="item.flow==='out' && conversation.type == 'GROUP'"
                     :src="item.avatar || 'https://sdk-web-1252463788.cos.ap-hongkong.myqcloud.com/component/TUIKit/assets/avatar_21.png'" @error="handleImageError(index)">
              </image>
            </view>
          </view>
        </view>
        <view v-else :id="item.ID" :data-value="item.ID">
          <TUI-SystemMessage :message="item" :lang="lang" :groupUser="groupUserDict"></TUI-SystemMessage>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script>
import TUITextMessage from "../message-elements/text-message/index";
import TUIImageMessage from "../message-elements/image-message/index";
import TUIVideoMessage from "../message-elements/video-message/index";
import TUIAudioMessage from "../message-elements/audio-message/index";
import TUICustomMessage from "../message-elements/custom-message/index";
import TUITipMessage from "../message-elements/tip-message/index";
import TUISystemMessage from "../message-elements/system-message/index";
import TUIFaceMessage from "../message-elements/face-message/index";
import TUIFileMessage from "../message-elements/file-message/index";
import {
  getTimeS,
  getHistoryChatTime
} from '../../../utils/date'
export default {
  data() {
    return {
      avatar: '',
      userID: '',
      // 当前会话
      messageList: [],
      // 自己的 ID 用于区分历史消息中，哪部分是自己发出的
      scrollView: '',
      scrollTop: 0,
      triggered: true,
      nextReqMessageID: '',
      // 下一条消息标志
      isCompleted: false // 当前会话消息是否已经请求完毕
      ,

      idx: 0,
      size: 20,
      count: 0,
      total: 0,
      isServerCompleted: false,

      gravity: 'top',

      groupUserDict: [],

      showName: '',
      RevokeID: '', // 撤回消息的ID用于处理对方消息展示界面
      isRevoke: false,
      isShowRevoke: false,
      tooltipShow: false,
      tooltipMsgId: '',
      tooltipMessage: {},
    };
  },

  components: {
    TUITextMessage,
    TUIImageMessage,
    TUIVideoMessage,
    TUIAudioMessage,
    TUICustomMessage,
    TUITipMessage,
    TUISystemMessage,
    TUIFaceMessage,
    TUIFileMessage,
  },
  props: {
    conversation: {
      type: Object,
      default: () => {}
    },
    lang: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    i18n() {
      return this.$i18n.locale
    }
  },
  watch: {
    conversation: {
      handler: function(newVal) {
        if (!newVal.conversationID) return;
        let that = this;
        that.getGroupUserList();
        that.getServerMessageCount();
        // that.setData({
        // 	conversation: newVal
        // }, () => {
        // 	setTimeout(function() {
        // 		that.getMessageList(newVal);
        // 	}, 800);
        // });
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    uni.$TUIKit.getMyProfile().then(res => {
      this.avatar = res.data.avatar;
      this.userID = res.data.userID;
    });
    uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived, this);
    uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_READ_BY_PEER, this.$onMessageReadByPeer, this);
    uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_REVOKED, this.onMessageRevoked, this);
  },
  destroyed() {
    // 一定要解除相关的事件绑定
    uni.$TUIKit.off(uni.$TUIKitEvent.MESSAGE_RECEIVED, this.$onMessageReceived);
    uni.$TUIKit.on(uni.$TUIKitEvent.MESSAGE_REVOKED, this.onMessageRevoked);
  },
  methods: {
    refresh() {
      if (this.isCompleted) {
        this.setData({
          isCompleted: true,
          triggered: false
        });

        //检查是否有历史消息
        if (!this.isServerCompleted) {
          this.getServerMessageList();
        }
        return;
      }
      this.getMessageList(this.conversation);
      setTimeout(() => {
        this.setData({
          triggered: false
        });
      }, 2000);
    },
    getHistoryChatTime,
    getMessageList(conversation) {
      if (!this.isCompleted) {
        uni.$TUIKit.getMessageList({
          conversationID: conversation.conversationID,
          nextReqMessageID: this.nextReqMessageID,
          count: 15
        }).then(res => {
          //console.log("res", res);
          const {
            messageList
          } = res.data; // 消息列表。
          this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
          this.isCompleted = res.data.isCompleted; // 表示是否已经拉完所有消息。
          this.messageList = [...messageList, ...this.messageList];
          //console.log("messageList", messageList);
          if (this.isCompleted) {
            this.getServerMessageList();
          }
          this.$handleMessageRender(this.messageList, messageList);
        });
      }
    },
    getServerMessageList() {
      let that = this;
      let query = {
        idx: that.idx,
        conversation_id: that.conversation.conversationID,
        conversation_type: that.conversation.type,
      };
      this.$http.get('/mgr/user/chat/record/data', query).then(res => {
        let list = res;
        that.idx = that.idx + 1;
        that.messageList = [...list, ...that.messageList];
        that.$handleMessageRender(that.messageList, list);

        //检查数据是否已拉取完
        if (Math.ceil(that.count / 15) <= that.idx) {
          // that.triggered = true;
          that.setData({
            triggered: true,
            isServerCompleted: true,
          });
          setTimeout(() => {
            that.setData({
              triggered: false
            });
          }, 2000);
        }
      });
    },
    getServerMessageCount() {
      let that = this;
      let query = {
        conversation_id: that.conversation.conversationID,
        conversation_type: that.conversation.type,
      };
      this.$http.get('/mgr/user/chat/record/data/count', query).then(res => {
        that.count = res;
      });
    },
    getGroupUserList() {
      let that = this;
      if (that.conversation.type == 'GROUP') {
        let query = {
          gid: that.conversation.groupProfile.groupID,
        };
        this.$http.get('/mgr/user/group/member/list/data', query).then(res => {
          let dict = [];
          for (let i = 0; i < res.groupMemberList.length; i++) {
            let userId = res.groupMemberList[i].User.toString();
            dict[userId] = res.groupMemberList[i] || {};
          }
          that.groupUserDict = dict;
        });
      }
      that.getMessageList(that.conversation);
    },

    // 自己的消息上屏
    updateMessageList(msg) {
      this.messageList = [...this.messageList, msg]
      this.scrollToButtom()
    },

    // 消息已读更新
    $onMessageReadByPeer() {
      this.setData({
        messageList: this.messageList
      });
    },
    scroll(e) {
      this.scrollTopPage = e.detail.scrollTop;
    },
    scrollToButtom() {
      const query = uni.createSelectorQuery().in(this);
      let nodesRef = query.select('#message-scroll');
      nodesRef.boundingClientRect(res => {
        this.$nextTick(() => {
          //进入页面滚动到底部
          this.scrollTop = res.height;
        });
      }).exec()
    },
    // 收到的消息
    $onMessageReceived(value) {
      // 若需修改消息，需将内存的消息复制一份，不能直接更改消息，防止修复内存消息，导致其他消息监听处发生消息错误
      const event = value;
      const list = [];
      event.data.forEach(item => {
        if (item.conversationID === this.conversation.conversationID) {
          list.push(Object.assign(item));
        }
      });
      this.messageList = this.messageList.concat(list);
      this.scrollToButtom()
    },
    // 向对方通知消息撤回事件
    $onMessageRevoked(event) {
      if (event.data[0].from !== this.vuex_user.timUserId) {
        this.setData({
          showName: event.data[0].nick,
          RevokeID: event.data[0].ID,
          isRevoke: true,
        });
      }
      this.updateMessageByID(event.data[0].ID);
    },

    // 历史消息渲染
    $handleMessageRender(messageList) {
      let that = this;
      if (messageList.length > 0) {
        this.setData({
          messageList,
        }, () => {});

        setTimeout(function() {
          that.$nextTick(() => {
            that.scrollTop = 99999;
          });
        }, 500);
        // this.$nextTick(() => {
        // 	setTimeout(function() {
        // 		// const query = uni.createSelectorQuery().in(this);
        // 		// let nodesRef = query.select('#message-scroll');
        // 		// nodesRef.boundingClientRect(res => {
        // 		// 	//进入页面滚动到底部
        // 		// }).exec()
        // 	}, 500);
        // });
      }
    },

    // 更新messagelist
    updateMessageByID(deleteMessageID) {
      const {
        messageList
      } = this;
      const deleteMessageArr = messageList.filter(item => item.ID === deleteMessageID);
      this.setData({
        messageList: messageList,
      });
      return deleteMessageArr;
    },
    handleLongPress(message) {
      if ((message.time + 24 * 3600) * 1000 > Date.now() && message.flow == 'out') {
        this.isShowRevoke = true;
      } else {
        this.isShowRevoke = false;
      }
      this.setData({
        tooltipMsgId: message.ID,
        tooltipMessage: message,
        tooltipShow: true,
      });
    },
    // 关闭弹窗
    handleEditToggleAvatar() {
      this.setData({
        tooltipShow: false,
      });
    },
    handleImageError(index, type) {
      if (type == 'GROUP' && this.groupUserDict[index]) {
        this.groupUserDict[index].UserAvatar = '../../../static/images/avatar.jpg';
      } else {
        this.messageList[index].avatar = '../../../static/images/avatar.jpg';
      }
    },
    copyMessage() {
      let that = this;
      uni.setClipboardData({
        data: this.tooltipMessage.payload.text,
        showToast: false,
        success: function() {
          uni.getClipboardData({
            success: function(res) {
              uni.showToast({
                title: that.lang.chat_copy_success,
                icon: 'none',
              });
            }
          })
        },
      });
    },
    deleteMessage() {
      let that = this;
      let promise = uni.$TUIKit.deleteMessage([this.tooltipMessage]);
      promise.then(function(imResponse) {
        that.updateMessageByID(imResponse.data.messageList[0].ID);
        uni.showToast({
          title: '删除成功',
          icon: 'none',
        });
      }).catch(function(imError) {
        // 删除消息失败
        uni.showToast({
          title: '删除失败',
          icon: 'none',
        });
      });
    },
    revokeMessage() {
      let that = this;
      let promise = uni.$TUIKit.revokeMessage(this.tooltipMessage);
      promise.then(function(imResponse) {
        // 撤销成功
        uni.showToast({
          title: that.lang.chat_recall_success,
          icon: 'none',
        });
      }).catch(function(imError) {
        uni.showToast({
          title: imError.message,
          icon: 'none',
        });
      });
    },
  }
};
</script>
<style>
@import "./index.css";
</style>
